package leetcode.method.bit_operation;

public class Program67BinarySum {

    public Program67BinarySum() {
    }

    public String addBinary(String a, String b) {
        if (a.length() == 0) {
            return b;
        }
        if (b.length() == 0) {
            return a;
        }

        int pre = 0;
        int i = a.length() - 1;
        int j = b.length() - 1;
        StringBuilder sb = new StringBuilder();
        while (i >= 0 && j >= 0) {
            int cur = pre + (a.charAt(i) - '0') + (b.charAt(j) - '0');
            sb.append(cur % 2);
            pre = cur / 2;
            i--;
            j--;
        }
        if (i < 0) {
            while (j >= 0) {
                int cur = pre + (b.charAt(j) - '0');
                sb.append(cur % 2);
                pre = cur / 2;
                j--;
            }
        }

        if (j < 0) {
            while (i >= 0) {
                int cur = pre + (a.charAt(i) - '0');
                sb.append(cur % 2);
                pre = cur / 2;
                i--;
            }
        }

        if (pre > 0) {
            sb.append(pre);
        }

        return  sb.reverse().toString();
    }

    public static void main(String[] args) {
        Program67BinarySum myStack = new Program67BinarySum();
        System.out.println(myStack.addBinary("11", "1"));
        System.out.println(myStack.addBinary("101", "11"));
    }
}
